package com.sevenluo.netty.learn.server.codec.handler;

import com.sevenluo.netty.learn.common.Operation;
import com.sevenluo.netty.learn.common.OperationResult;
import com.sevenluo.netty.learn.common.RequestMessage;
import com.sevenluo.netty.learn.common.ResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: 程序员七哥
 * @date: 2022-01-26
 * @description: 读取并处理解码后的消息，因为我们的协议类解码器已经将消息转为了 RequestMessage
 */
@Slf4j
public class OrderServerProcessHandler extends SimpleChannelInboundHandler<RequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestMessage msg) throws Exception {

        // 模拟制造内存泄漏
        // ByteBuf buffer = ctx.alloc().buffer();

        Operation operation = msg.getMessageBody();
        OperationResult result = operation.execute();

        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setMessageHeader(msg.getMessageHeader());
        responseMessage.setMessageBody(result);

        // 避免 OOM，在超过高低水位线或者触发流量整形时，就不要在写了
        if (ctx.channel().isActive() && ctx.channel().isWritable()) {
            // 将消息通过 channel 写出去
            ctx.writeAndFlush(responseMessage);
        } else {
            log.warn("message is drop,need to save!");
        }

    }
}
